import sys
import os
from datetime import datetime
from PyQt6.QtCore import QUrl, Qt, QSize
from PyQt6.QtWidgets import (QApplication, QMainWindow, QLineEdit, QPushButton, 
                           QVBoxLayout, QWidget, QHBoxLayout, QLabel, 
                           QProgressBar, QMenu, QToolBar, QStatusBar,
                           QDialog, QInputDialog, QListWidget, QMessageBox,
                           QTextEdit, QSplitter)
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebEngineCore import (QWebEnginePage, QWebEngineProfile, 
                                  QWebEngineSettings, QWebEngineUrlRequestInterceptor)
from PyQt6.QtGui import QIcon, QFont, QPixmap, QAction

class CustomWebEnginePage(QWebEnginePage):
    def __init__(self, profile, parent=None):
        super().__init__(profile, parent)
        # 创建历史堆栈来手动跟踪历史
        self.history_stack = []
        self.current_history_index = -1
        self.last_url = None
        
    def acceptNavigationRequest(self, url, navigation_type, is_main_frame):
        """处理导航请求，确保链接点击能正常工作"""
        url_str = url.toString()
        # 导航类型: 0=链接点击, 1=后退/前进, 2=重新加载, 3=表单提交, 4=其他
        print(f"导航请求: {url_str}, 类型: {navigation_type}, 主框架: {is_main_frame}")
        
        # 只处理主框架的导航
        if is_main_frame:
            # 如果是链接点击或重定向，则添加到历史记录中
            if (navigation_type == QWebEnginePage.NavigationType.NavigationTypeLinkClicked or 
                navigation_type == QWebEnginePage.NavigationType.NavigationTypeRedirect):
                # 避免重复添加相同URL
                if self.last_url != url_str:
                    # 如果我们在历史中的某个位置（不是最后），则截断历史记录
                    if self.current_history_index < len(self.history_stack) - 1:
                        self.history_stack = self.history_stack[:self.current_history_index + 1]
                    
                    # 添加新URL到历史记录
                    self.history_stack.append(url_str)
                    self.current_history_index = len(self.history_stack) - 1
                    self.last_url = url_str
                    print(f"添加到历史: {url_str}, 当前索引: {self.current_history_index}")
            
        return True
    
    def createWindow(self, window_type):
        """处理新窗口请求，在当前窗口打开"""
        print(f"创建窗口请求，类型: {window_type}")
        return self
        
    def can_go_back(self):
        """检查是否可以后退"""
        return self.current_history_index > 0
        
    def can_go_forward(self):
        """检查是否可以前进"""
        return self.current_history_index < len(self.history_stack) - 1
        
    def go_back(self):
        """后退到历史记录中的上一页"""
        if self.can_go_back():
            self.current_history_index -= 1
            url = self.history_stack[self.current_history_index]
            print(f"后退到: {url}, 当前索引: {self.current_history_index}")
            self.load(QUrl(url))
            return True
        return False
        
    def go_forward(self):
        """前进到历史记录中的下一页"""
        if self.can_go_forward():
            self.current_history_index += 1
            url = self.history_stack[self.current_history_index]
            print(f"前进到: {url}, 当前索引: {self.current_history_index}")
            self.load(QUrl(url))
            return True
        return False

class Browser(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('轻量级前端测试浏览器')
        self.setGeometry(100, 100, 1024, 768)
        
        # 初始化书签列表
        self.bookmarks = {}
        
        # 初始化浏览日志
        self.browsing_log = []

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.layout = QVBoxLayout(self.central_widget)
        self.layout.setContentsMargins(5, 5, 5, 5)
        self.layout.setSpacing(5)
        
        # 创建顶部工具栏
        self.nav_layout = QHBoxLayout()
        self.nav_layout.setSpacing(2)
        
        # 后退按钮
        self.back_button = QPushButton('←')
        self.back_button.setToolTip('后退')
        self.back_button.clicked.connect(self.browser_back)
        self.back_button.setFixedSize(36, 36)
        self.back_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.back_button)
        
        # 前进按钮
        self.forward_button = QPushButton('→')
        self.forward_button.setToolTip('前进')
        self.forward_button.clicked.connect(self.browser_forward)
        self.forward_button.setFixedSize(36, 36)
        self.forward_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.forward_button)
        
        # 刷新按钮
        self.refresh_button = QPushButton('⟳')
        self.refresh_button.setToolTip('刷新')
        self.refresh_button.clicked.connect(self.browser_reload)
        self.refresh_button.setFixedSize(36, 36)
        self.refresh_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.refresh_button)
        
        # 停止按钮
        self.stop_button = QPushButton('✕')
        self.stop_button.setToolTip('停止')
        self.stop_button.clicked.connect(self.browser_stop)
        self.stop_button.setFixedSize(36, 36)
        self.stop_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.stop_button)
        
        # 首页按钮
        self.home_button = QPushButton('🏠')
        self.home_button.setToolTip('首页')
        self.home_button.clicked.connect(self.go_home)
        self.home_button.setFixedSize(36, 36)
        self.home_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.home_button)

        # URL地址栏
        self.url_bar = QLineEdit()
        self.url_bar.setPlaceholderText("输入网址或搜索内容...")
        self.url_bar.returnPressed.connect(self.navigate_to_url)
        self.nav_layout.addWidget(self.url_bar, 1)  # 地址栏占据剩余空间
        
        # Go按钮
        self.go_button = QPushButton('转到')
        self.go_button.setToolTip('转到此网址')
        self.go_button.clicked.connect(self.navigate_to_url)
        self.nav_layout.addWidget(self.go_button)
        
        # 书签按钮
        self.bookmark_button = QPushButton('★')
        self.bookmark_button.setToolTip('添加/管理书签')
        self.bookmark_button.clicked.connect(self.toggle_bookmark)
        self.bookmark_button.setFixedSize(36, 36)
        self.bookmark_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.bookmark_button)
        
        # 浏览日志按钮
        self.log_button = QPushButton('📋')
        self.log_button.setToolTip('查看浏览日志')
        self.log_button.clicked.connect(self.show_browsing_log)
        self.log_button.setFixedSize(36, 36)
        self.log_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.log_button)
        
        # 查看源码按钮
        self.source_button = QPushButton('📄')
        self.source_button.setToolTip('查看网页源代码')
        self.source_button.clicked.connect(self.show_page_source)
        self.source_button.setFixedSize(36, 36)
        self.source_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.source_button)
        
        # 开发者工具按钮
        self.dev_tools_button = QPushButton('🔧')
        self.dev_tools_button.setToolTip('开发者工具')
        self.dev_tools_button.clicked.connect(self.toggle_dev_tools)
        self.dev_tools_button.setFixedSize(36, 36)
        self.dev_tools_button.setFont(QFont('Arial', 14))
        self.nav_layout.addWidget(self.dev_tools_button)
        
        # 将导航栏添加到主布局
        self.layout.addLayout(self.nav_layout)

        # 初始化浏览器组件
        self.browser = QWebEngineView()
        
        # 创建自定义页面来处理导航
        profile = QWebEngineProfile.defaultProfile()
        self.custom_page = CustomWebEnginePage(profile, self.browser)
        self.browser.setPage(self.custom_page)
        
        # 监听URL变化，同步更新地址栏
        self.browser.urlChanged.connect(self.update_url_bar)
        
        # 添加进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setMaximumHeight(2)
        self.progress_bar.setTextVisible(False)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                background-color: #F0F0F0;
                border: none;
            }
            QProgressBar::chunk {
                background-color: #4CAF50;
            }
        """)
        self.layout.addWidget(self.progress_bar)
        
        # 添加浏览器视图
        self.layout.addWidget(self.browser, 1)  # 浏览器视图占据主要空间
        
        # 创建状态栏
        self.status_bar = QStatusBar()
        self.status_bar.setFixedHeight(24)
        self.setStatusBar(self.status_bar)
        
        # 状态标签
        self.status_label = QLabel("就绪")
        self.status_bar.addWidget(self.status_label)
        
        # 监听加载进度
        self.browser.loadProgress.connect(self.update_progress)

        # 配置浏览器设置 - PyQt6版本中的修改
        profile = self.browser.page().profile()
        profile.setHttpCacheType(QWebEngineProfile.HttpCacheType.NoCache)
        profile.setPersistentCookiesPolicy(QWebEngineProfile.PersistentCookiesPolicy.NoPersistentCookies)
        
        # 启用JavaScript和其他Web功能以确保链接正常工作 - PyQt6版本中的修改
        settings = self.browser.settings()
        settings.setAttribute(QWebEngineSettings.WebAttribute.JavascriptEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.LinksIncludedInFocusChain, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.SpatialNavigationEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.TouchIconsEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.FocusOnNavigationEnabled, True)
        
        # 启用更多Web功能 - PyQt6版本中的修改
        settings.setAttribute(QWebEngineSettings.WebAttribute.PluginsEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.FullScreenSupportEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.ScreenCaptureEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.WebGLEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.Accelerated2dCanvasEnabled, True)
        settings.setAttribute(QWebEngineSettings.WebAttribute.AutoLoadIconsForPage, True)
        
        # 监听页面加载完成事件
        self.browser.loadFinished.connect(self.page_load_finished)
        
        # 监听链接点击事件
        self.browser.page().linkHovered.connect(self.link_hovered)
        
        # 添加导航信号连接，确保正确追踪历史记录
        self.browser.navigationRequested = self.browser.page().navigationRequested

        # 监听导航状态变化，用于更新按钮状态
        self.browser.loadStarted.connect(self.update_navigation_buttons)
        self.browser.loadFinished.connect(self.update_navigation_buttons)
        self.browser.urlChanged.connect(self.update_navigation_buttons)
        
        # 设置默认首页
        self.home_url = "https://www.baidu.com"
        
        # 开发者工具窗口
        self.dev_tools = QWebEngineView()
        self.dev_tools.setWindowTitle('Developer Tools')
        self.dev_tools.hide()
        
        # 尝试加载保存的书签和日志
        self.load_bookmarks()
        self.load_browsing_log()

    def toggle_dev_tools(self):
        if self.dev_tools.isHidden():
            # 使用 setDevToolsPage 方法而不是 createDevToolsPage
            self.browser.page().setDevToolsPage(self.dev_tools.page())
            self.dev_tools.setGeometry(100, 100, 800, 600)
            self.dev_tools.show()
        else:
            self.dev_tools.hide()

    def update_url_bar(self, url):
        """当页面URL变化时更新地址栏"""
        url_str = url.toString()
        self.url_bar.setText(url_str)
        
        # 记录URL到浏览日志
        self.add_to_log(url_str)
    
    def add_to_log(self, url):
        """将URL添加到浏览日志"""
        if url and url.startswith(('http://', 'https://')):
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            log_entry = {
                'timestamp': timestamp,
                'url': url,
                'title': ''  # 暂时为空，会在页面加载完成后更新
            }
            self.browsing_log.append(log_entry)
            self.save_browsing_log()
    
    def link_hovered(self, url):
        """当鼠标悬停在链接上时的处理"""
        if url:
            print(f"悬停链接: {url}")
    
    def browser_back(self):
        """后退到上一页"""
        # 使用我们自定义的历史系统
        if self.custom_page.can_go_back():
            print("使用自定义历史系统后退")
            self.custom_page.go_back()
        else:
            print("无法后退：历史记录已到达开始位置")
    
    def browser_forward(self):
        """前进到下一页"""
        # 使用我们自定义的历史系统
        if self.custom_page.can_go_forward():
            print("使用自定义历史系统前进")
            self.custom_page.go_forward()
        else:
            print("无法前进：历史记录已到达最新位置")
    
    def browser_reload(self):
        """重新加载当前页面"""
        self.browser.reload()
    
    def browser_stop(self):
        """停止当前页面加载"""
        self.browser.stop()
    
    def go_home(self):
        """前往首页"""
        self.browser.setUrl(QUrl(self.home_url))
    
    def update_progress(self, progress):
        """更新加载进度"""
        self.progress_bar.setValue(progress)
        if progress == 100:
            # 加载完成后隐藏进度条
            self.progress_bar.hide()
        else:
            self.progress_bar.show()
        
        # 更新状态栏信息
        if progress < 100:
            self.status_label.setText(f"加载中... ({progress}%)")
        else:
            self.status_label.setText("加载完成")
    
    def toggle_bookmark(self):
        """添加或管理书签"""
        current_url = self.browser.url().toString()
        current_title = self.browser.page().title()
        
        if current_url in self.bookmarks:
            # 如果当前URL已经是书签，询问是否删除
            reply = QMessageBox.question(self, '书签管理', 
                                          f'"{current_title}" 已在书签中，是否删除?',
                                          QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, 
                                          QMessageBox.StandardButton.No)
            if reply == QMessageBox.StandardButton.Yes:
                del self.bookmarks[current_url]
                self.save_bookmarks()
                self.status_label.setText(f'已从书签中删除 "{current_title}"')
            else:
                # 显示所有书签
                self.show_bookmarks()
        else:
            # 如果当前URL不是书签，添加它
            if current_url.startswith(('http://', 'https://')):
                self.bookmarks[current_url] = current_title
                self.save_bookmarks()
                self.status_label.setText(f'已添加书签: "{current_title}"')
            else:
                self.status_label.setText('无法为空白页添加书签')
    
    def show_bookmarks(self):
        """显示书签管理窗口"""
        # 如果没有书签，显示消息
        if not self.bookmarks:
            QMessageBox.information(self, '书签管理', '没有保存的书签')
            return
        
        # 创建书签列表对话框
        dialog = QDialog(self)
        dialog.setWindowTitle('书签管理')
        dialog.setMinimumSize(400, 300)
        
        layout = QVBoxLayout(dialog)
        bookmark_list = QListWidget()
        
        # 添加所有书签到列表
        for url, title in self.bookmarks.items():
            bookmark_list.addItem(f"{title} - {url}")
        
        layout.addWidget(bookmark_list)
        
        # 添加按钮行
        button_layout = QHBoxLayout()
        open_button = QPushButton('打开')
        delete_button = QPushButton('删除')
        close_button = QPushButton('关闭')
        
        button_layout.addWidget(open_button)
        button_layout.addWidget(delete_button)
        button_layout.addWidget(close_button)
        layout.addLayout(button_layout)
        
        # 连接按钮信号
        def open_bookmark():
            selected_items = bookmark_list.selectedItems()
            if selected_items:
                item_text = selected_items[0].text()
                url = item_text.split(' - ')[-1]
                self.browser.setUrl(QUrl(url))
                dialog.accept()
        
        def delete_bookmark():
            selected_items = bookmark_list.selectedItems()
            if selected_items:
                item_text = selected_items[0].text()
                url = item_text.split(' - ')[-1]
                if url in self.bookmarks:
                    del self.bookmarks[url]
                    bookmark_list.takeItem(bookmark_list.currentRow())
                    self.save_bookmarks()
        
        open_button.clicked.connect(open_bookmark)
        delete_button.clicked.connect(delete_bookmark)
        close_button.clicked.connect(dialog.reject)
        
        # 双击列表项也打开书签
        bookmark_list.itemDoubleClicked.connect(lambda: open_bookmark())
        
        dialog.exec()
    
    def save_bookmarks(self):
        """保存书签到文件"""
        try:
            with open('bookmarks.txt', 'w', encoding='utf-8') as f:
                for url, title in self.bookmarks.items():
                    f.write(f"{url}|{title}\n")
        except Exception as e:
            print(f"保存书签失败: {e}")
    
    def load_bookmarks(self):
        """从文件加载书签"""
        try:
            if os.path.exists('bookmarks.txt'):
                with open('bookmarks.txt', 'r', encoding='utf-8') as f:
                    for line in f:
                        if '|' in line:
                            url, title = line.strip().split('|', 1)
                            self.bookmarks[url] = title
        except Exception as e:
            print(f"加载书签失败: {e}")
    
    def update_navigation_buttons(self):
        """更新导航按钮状态"""
        # 更新后退按钮状态 - 使用我们的自定义历史系统
        self.back_button.setEnabled(self.custom_page.can_go_back())
        
        # 更新前进按钮状态 - 使用我们的自定义历史系统
        self.forward_button.setEnabled(self.custom_page.can_go_forward())
        
        # 更新停止按钮状态 - 只在加载过程中启用
        self.stop_button.setEnabled(self.browser.page().action(QWebEnginePage.WebAction.Stop).isEnabled())
        
        # 当页面加载时启用刷新按钮
        self.refresh_button.setEnabled(True)
        
        # 更新书签按钮样式
        current_url = self.browser.url().toString()
        if current_url in self.bookmarks:
            self.bookmark_button.setStyleSheet("color: gold; font-weight: bold;")
        else:
            self.bookmark_button.setStyleSheet("")
    
    def page_load_finished(self, success):
        """页面加载完成后的处理"""
        if success:
            current_url = self.browser.url().toString()
            print(f"页面加载成功: {current_url}")
            
            # 更新日志中最新条目的标题
            if self.browsing_log and self.browsing_log[-1]['url'] == current_url:
                page_title = self.browser.page().title()
                self.browsing_log[-1]['title'] = page_title
                self.save_browsing_log()
            
            # 注入JavaScript来增强链接点击处理，并确保导航历史正确更新
            js_code = """
            document.addEventListener('click', function(e) {
                let linkElement = e.target.tagName === 'A' ? e.target : e.target.closest('a');
                if (linkElement) {
                    let href = linkElement.href;
                    console.log('链接被点击:', href);
                    // 将链接点击事件标记为可能的导航
                    window.history.pushState({}, '', href);
                }
            });
            """
            self.browser.page().runJavaScript(js_code)
            
            # 确保导航按钮状态更新
            self.update_navigation_buttons()
        else:
            print(f"页面加载失败: {self.browser.url().toString()}")
    
    def show_browsing_log(self):
        """显示浏览日志窗口"""
        if not self.browsing_log:
            QMessageBox.information(self, '浏览日志', '暂无浏览记录')
            return
        
        # 创建日志对话框
        dialog = QDialog(self)
        dialog.setWindowTitle('浏览日志')
        dialog.setMinimumSize(600, 400)
        
        layout = QVBoxLayout(dialog)
        
        # 创建日志列表
        log_list = QListWidget()
        
        # 添加所有日志条目（倒序显示，最新的在前）
        for log_entry in reversed(self.browsing_log):
            timestamp = log_entry['timestamp']
            url = log_entry['url']
            title = log_entry['title'] if log_entry['title'] else '未知标题'
            log_list.addItem(f"[{timestamp}] {title}\n{url}")
        
        layout.addWidget(log_list)
        
        # 添加按钮行
        button_layout = QHBoxLayout()
        visit_button = QPushButton('访问')
        clear_button = QPushButton('清空日志')
        export_button = QPushButton('导出日志')
        close_button = QPushButton('关闭')
        
        button_layout.addWidget(visit_button)
        button_layout.addWidget(clear_button)
        button_layout.addWidget(export_button)
        button_layout.addWidget(close_button)
        layout.addLayout(button_layout)
        
        # 连接按钮信号
        def visit_selected():
            selected_items = log_list.selectedItems()
            if selected_items:
                item_text = selected_items[0].text()
                # 从文本中提取URL（第二行）
                lines = item_text.split('\n')
                if len(lines) >= 2:
                    url = lines[1]
                    self.browser.setUrl(QUrl(url))
                    dialog.accept()
        
        def clear_log():
            reply = QMessageBox.question(dialog, '确认', '确定要清空所有浏览日志吗？',
                                        QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, 
                                        QMessageBox.StandardButton.No)
            if reply == QMessageBox.StandardButton.Yes:
                self.browsing_log.clear()
                self.save_browsing_log()
                log_list.clear()
                QMessageBox.information(dialog, '成功', '浏览日志已清空')
        
        def export_log():
            try:
                filename = f"browsing_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write("浏览器访问日志\n")
                    f.write("=" * 50 + "\n\n")
                    for log_entry in reversed(self.browsing_log):
                        f.write(f"时间: {log_entry['timestamp']}\n")
                        f.write(f"标题: {log_entry['title']}\n")
                        f.write(f"网址: {log_entry['url']}\n")
                        f.write("-" * 30 + "\n\n")
                QMessageBox.information(dialog, '导出成功', f'日志已导出到文件: {filename}')
            except Exception as e:
                QMessageBox.warning(dialog, '导出失败', f'导出日志时发生错误: {str(e)}')
        
        visit_button.clicked.connect(visit_selected)
        clear_button.clicked.connect(clear_log)
        export_button.clicked.connect(export_log)
        close_button.clicked.connect(dialog.reject)
        
        # 双击列表项也访问URL
        log_list.itemDoubleClicked.connect(lambda: visit_selected())
        
        dialog.exec()
    
    def show_page_source(self):
        """显示当前页面的HTML源代码"""
        current_url = self.browser.url().toString()
        
        if not current_url.startswith(('http://', 'https://')):
            QMessageBox.warning(self, '无法查看源码', '当前页面无法查看源代码')
            return
        
        # 创建源码查看对话框
        dialog = QDialog(self)
        dialog.setWindowTitle(f'网页源代码 - {current_url}')
        dialog.setMinimumSize(800, 600)
        
        layout = QVBoxLayout(dialog)
        
        # 创建文本编辑器显示源码
        source_text = QTextEdit()
        source_text.setReadOnly(True)
        source_text.setFont(QFont('Consolas', 9))  # 使用等宽字体
        source_text.setPlainText('正在获取页面源代码...')
        
        layout.addWidget(source_text)
        
        # 添加按钮行
        button_layout = QHBoxLayout()
        save_button = QPushButton('保存源码')
        copy_button = QPushButton('复制全部')
        close_button = QPushButton('关闭')
        
        button_layout.addWidget(save_button)
        button_layout.addWidget(copy_button)
        button_layout.addWidget(close_button)
        layout.addLayout(button_layout)
        
        # 获取页面HTML源码
        def handle_html(html):
            source_text.setPlainText(html)
        
        self.browser.page().toHtml(handle_html)
        
        # 连接按钮信号
        def save_source():
            try:
                filename = f"page_source_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write(source_text.toPlainText())
                QMessageBox.information(dialog, '保存成功', f'源代码已保存到文件: {filename}')
            except Exception as e:
                QMessageBox.warning(dialog, '保存失败', f'保存源代码时发生错误: {str(e)}')
        
        def copy_source():
            clipboard = QApplication.clipboard()
            clipboard.setText(source_text.toPlainText())
            QMessageBox.information(dialog, '复制成功', '源代码已复制到剪贴板')
        
        save_button.clicked.connect(save_source)
        copy_button.clicked.connect(copy_source)
        close_button.clicked.connect(dialog.reject)
        
        dialog.exec()
    
    def save_browsing_log(self):
        """保存浏览日志到文件"""
        try:
            with open('browsing_log.txt', 'w', encoding='utf-8') as f:
                for log_entry in self.browsing_log:
                    f.write(f"{log_entry['timestamp']}|{log_entry['url']}|{log_entry['title']}\n")
        except Exception as e:
            print(f"保存浏览日志失败: {e}")
    
    def load_browsing_log(self):
        """从文件加载浏览日志"""
        try:
            if os.path.exists('browsing_log.txt'):
                with open('browsing_log.txt', 'r', encoding='utf-8') as f:
                    for line in f:
                        parts = line.strip().split('|')
                        if len(parts) >= 3:
                            log_entry = {
                                'timestamp': parts[0],
                                'url': parts[1],
                                'title': parts[2] if len(parts) > 2 else ''
                            }
                            self.browsing_log.append(log_entry)
        except Exception as e:
            print(f"加载浏览日志失败: {e}")
    
    def navigate_to_url(self):
        url = self.url_bar.text()
        
        # 如果输入为空，加载首页
        if not url.strip():
            self.go_home()
            return
        
        # 如果不是URL，用百度搜索
        if not url.startswith(('http://', 'https://')):
            if '.' in url and ' ' not in url:
                url = 'http://' + url
            else:
                # 将输入内容作为搜索查询
                search_query = url.replace(' ', '+')
                url = f"https://www.baidu.com/s?wd={search_query}"
        
        self.browser.setUrl(QUrl(url))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    browser = Browser()
    browser.show()
    sys.exit(app.exec())